<?php
// 应用公共文件
use app\common\core\FileHand;

if(!function_exists('success')){
    /**
     * 成功返回
     * @param string|array $msg 提示信息|数据
     * @param array|null $data 数据
     * @param string|int $code 业务编码
     * @param string $url 跳转地址
     * @return \think\response\Json
     */
    function success(string|array $msg='获取成功',array|null $data=null,string|int $code=1,string $url='')
    {
        if(is_array($msg)){
            $data = $msg;
            $msg = '获取成功';
        }
        $back = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'time' => time(),
            'url' => $url
        ];
        return json($back);
    }
}

if(!function_exists('error')){
    /**
     * 错误返回
     * @param string|array|int $msg 提示信息|业务编码|数据
     * @param string|int $code 业务编码
     * @param array|null $data 数据
     * @param string $url 跳转地址
     * @return \think\response\Json
     */
    function error(string|array|int $msg='获取失败',string|int $code=0,array $data=null,string $url='')
    {
        if(is_array($msg)){
            $data = $msg;
            $msg = '获取失败';
        }
        if(is_numeric($msg)){
            $code = $msg;
            $msg = '获取失败';
        }
        $back = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'time' => time(),
            'url' => $url
        ];
        return json($back);
    }
}

if(!function_exists('get_addons_list')){
    /**
     * 获取插件列表
     * @param bool $state 状态
     * @param bool $force 强制更新
     * @return array|mixed|null
     */
    function get_addons_list($state=true,$force=false)
    {
        if($state){
            $cache = \think\facade\Cache::get(\app\common\service\AddonService::ADDONS_STATE_KEY);
        }else{
            $cache = \think\facade\Cache::get(\app\common\service\AddonService::ADDONS_ALL_KEY);
        }
        if(\think\facade\Env::get('app_debug')||$force||empty($cache)){
            $addon_dir = app()->getRootPath().'addons'.DIRECTORY_SEPARATOR;
            $cache = \app\common\core\FileHand::init()->get_dir_path($addon_dir,'dir');
            if($state){
                $cache = array_filter($cache,function($item)use($addon_dir){
                    if(is_file($addon_dir.$item.'/info.ini')){
                        $info = parse_ini_file($addon_dir.$item.'/info.ini');
                        if(isset($info['state'])&&$info['state']==1){
                            return true;
                        }
                    }
                    return false;
                });
                \think\facade\Cache::set(\app\common\service\AddonService::ADDONS_STATE_KEY,$cache);
            }else{
                \think\facade\Cache::set(\app\common\service\AddonService::ADDONS_ALL_KEY,$cache);
            }
        }
        return $cache;
    }
}
if(!function_exists('get_addons_files')){
    function get_addons_files($force=false)
    {
        $addons_list = get_addons_list();
        if(empty($addons_list)){
            return [];
        }
        foreach ($addons_list as $key => $value) {
            $cache[$value] = [];
            $addon_value_dir = app()->getRootPath().'addons'.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR;
            // 服务配置
            $service = $addon_value_dir.'service.php';
            if(is_file($service)){
                $cache[$value]['base_service'] = require $service;
            }
            // 中间件配置
            $middleware = $addon_value_dir.'middleware.php';
            if(is_file($middleware)){
                $cache[$value]['base_middleware'] = require $middleware;
            }
            // 事件配置
            $event = $addon_value_dir.'event.php';
            if(is_file($event)){
                $cache[$value]['base_event'] = require $event;
            }
            // 命令配置
            $command = $addon_value_dir.'command.php';
            if(is_file($command)){
                $cache[$value]['base_command'] = require $command;
            }
            //函数文件直接引入
            $common = $addon_value_dir.'common.php';
            if(is_file($common)){
                include $common;
            }
            // 路由文件直接引入
            $route = $addon_value_dir.'route.php';
            if(is_file($route)){
//                    echo '有路由文件';
                include $route;
            }
            $childFiles = \app\common\core\FileHand::init()->get_dir_path($addon_value_dir,'dir',[
                'common',
                'route',
                'service',
                'middleware',
                'event',
                'command'
            ],[

            ],false,true);
            foreach ($childFiles as $values){
                $addon_child_dir = $addon_value_dir.$values.DIRECTORY_SEPARATOR;
                $child_service = $addon_child_dir.'service.php';
                if(is_file($child_service)){
                    $cache[$value]['child_service'][$values] = require $child_service;
                }
                $child_middleware = $addon_child_dir.'middleware.php';
                if(is_file($child_middleware)){
                    $cache[$value]['child_middleware'][$values] = require $child_middleware;
                }
                $child_event = $addon_child_dir.'event.php';
                if(is_file($child_event)){
                    $cache[$value]['child_event'][$values] = require $child_event;
                }
                $child_command = $addon_child_dir.'command.php';
                if(is_file($child_command)){
                    $cache[$value]['child_command'][$values] = require $child_command;
                }
                $child_common = $addon_child_dir.'common.php';
                if(is_file($child_common)){
                    include $child_common;
                }
                $child_route = $addon_child_dir.'route.php';
                if(is_file($child_route)){
                    include $child_route;
                }
            }
        }
    }
}

if(!function_exists('get_addons_info')){
    /**
     * 获取插件信息
     * @param string $name
     * @return array|mixed|null
     */
    function get_addons_info($name='')
    {
        $addons_list = get_addons_list();
        if(empty($addons_list)){
            return [];
        }
        $info = [];
        if(!empty($name)){
            if(in_array($name,$addons_list)){
                $addon_dir = app()->getRootPath().'addons'.DIRECTORY_SEPARATOR.$name.DIRECTORY_SEPARATOR;
                if(is_file($addon_dir.'info.ini')){
                    $info = parse_ini_file($addon_dir.'info.ini');
                }
            }
            return $info;
        }else{
            foreach ($addons_list as $key => $value) {
                $addon_dir = app()->getRootPath().'addons'.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR;
                if(is_file($addon_dir.'info.ini')){
                    $info[$value] = parse_ini_file($addon_dir.'info.ini');
                }
            }
            return $info;
        }
    }
}

if(!function_exists('clearAddonsCache')){
    /**
     * 清理插件缓存
     * @return true
     */
    function clearAddonsCache()
    {
        return app()->make(\app\common\service\AddonService::class)->clearAddonsCache();
    }
}
/**
 * 获取插件类名
 */
if(!function_exists('get_addon_class')){
    function get_addon_class($addons,$type,$module,$class)
    {
        $addons = strtolower($addons);
        $module = strtolower($module);
        $type = strtolower($type);
        if(strpos($class,'.')!=false){
            $class_array = explode('.',$class);
        }else{
            $class_array = explode('/',$class);
        }
        $class_array = array_filter($class_array);
        $class_array[count($class_array)-1] = ucfirst($class_array[count($class_array)-1]);
        $class_name = "\\addons\\{$addons}\\app\\{$module}\\{$type}\\".implode('\\',$class_array);
        if(class_exists($class_name)){
            return [true,$class_name];
        }
        return [false,$class_name.'类不存在'];
    }
}

/**
 * 获取
 */
if (! function_exists('parseName')) {
    function parseName($name, $type = 0, $ucfirst = true)
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);

            return $ucfirst ? ucfirst($name) : lcfirst($name);
        }

        return strtolower(trim(preg_replace('/[A-Z]/', '_\\0', $name), '_'));
    }
}

if (! function_exists('__')) {

    /**
     * 获取语言变量值
     *
     * @param  string  $name  语言变量名
     * @param  array  $vars  动态变量值
     * @param  string  $lang  语言
     *
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || ! $name) {
            return $name;
        }
        if (! is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\facade\Lang::get($name, $vars, $lang);
    }
}
/**
 * 获取应用映射
 */
if(!function_exists('get_app_map')){
    function get_app_map($app_name='',$is_key=false)
    {
        if(!empty($app_name)){
            $all_map = app()->config->get('app.app_map');
            if($is_key){
                if(isset($all_map[$app_name])){
                    return $all_map[$app_name];
                }
                return $app_name;
            }else{
                $key = array_search($app_name,$all_map);
                if($key!=false){
                    return $key;
                }
                return $app_name;
            }

        }
        return app()->config->get('app.app_map');
    }
}

/**
 * 判断 文件/目录 是否可写（取代系统自带的 is_writeable 函数）
 *
 * @param string $file 文件/目录
 * @return boolean
 */
function is_write($file)
{
    if (is_dir($file)) {
        $dir = $file;
        if ($fp = @fopen("$dir/test.txt", 'wb')) {
            @fclose($fp);
            @unlink("$dir/test.txt");
            $writeable = true;
        } else {
            $writeable = false;
        }
    } else {
        if ($fp = @fopen($file, 'ab+')) {
            @fclose($fp);
            $writeable = true;
        } else {
            $writeable = false;
        }
    }
    return $writeable;
}

/**
 * 获取唯一随机字符串
 * @param int $len
 * @return string
 */
function unique_random($len = 10)
{
    $str = 'qwertyuiopasdfghjklzxcvbnmasdfgh9521478630';
    str_shuffle($str);
    return substr(str_shuffle($str), 0, $len);
}
/**
 * 生成加密密码
 * @param $password
 * @param $salt  手动提供散列密码的盐值（salt）。这将避免自动生成盐值（salt）。,默认不填写将自动生成
 * @return string
 */
function create_password($password, $salt = '')
{
    return password_hash($password.$salt, PASSWORD_DEFAULT);
}
/**
 * 校验比对密码和加密密码是否一致
 * @param $password
 * @param $hash
 * @return bool
 */
function check_password($password, $hash, $salt = '')
{
    if (!password_verify($password.$salt, $hash)) return false;
    return true;
}


/**
 * 把返回的数据集转换成Tree
 * @param $list 要转换的数据集
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[ $data[ $pk ] ] =& $list[ $key ];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parent_id = $data[ $pid ];
            if ($root == $parent_id) {
                $tree[] =& $list[ $key ];
            } else {
                if (isset($refer[ $parent_id ])) {
                    $parent =& $refer[ $parent_id ];
                    $parent[ $child ][] =& $list[ $key ];
                }
            }
        }
    }
    return $tree;

}
if(!function_exists('redirectv2')){
    function redirectv2($url, $params = [], $code = 302, $with = [])
    {
        $url = strtolower($url);
        if (is_int($params)) {
            $code = $params;
        }
        $response = \redirect($url);
        $response->code($code)->with($with);

        throw new HttpResponseException($response);
    }
}
if (! function_exists('upload_file')) {
    /**
     * 上传文件.
     *
     * @param  string  $file  上传的文件
     * @param  string  $name  上传的位置
     * @param  string  $path  上传的文件夹
     * @param  string  $validate  规则验证
     * @param  string  $url  前缀
     *
     * @return string|bool
     * @author niu
     */
    function upload_file($file = null, $name = 'local', $path = '', $validate = '', $url = '/')
    {
        //文件
        if (! $file) {
            return false;
        }
        //上传配置
        $config_name = 'filesystem.disks.'.$name;
        $filesystem = config($config_name);
        if (! $filesystem) {
            return false;
        }
        //上传文件
        if ($validate) {
            validate(['file' => $validate])->check(['file' => $file]);
        }
        $savename = \think\facade\Filesystem::disk($name)->putFile($path, $file, function ($file) {
            //重命名
            return date('Ymd').'/'.md5((string) microtime(true));
        });
        if(empty($url)){
            $url = '/';
        }
        $savename = $url.$savename;

        return $savename;
    }
}


if(!function_exists('get_app_list')){
    function get_app_list()
    {
        $dir = root_path().'app';
        $dirs = FileHand::init()->get_dir_path($dir,'dir',['common','install']);
        return $dirs;
    }
}